package com.example.mypra1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 用户访问app时通过token
 * 判断是否需重新登录
 */
public class MainActivity extends AppCompatActivity {
    class User{
        private int id;
        private String username;
        private String phone;
        private String password;
        private String profile;
        private int sex;
        private String zodiac;//生肖
        private String constellation;//星座

        //用户实体类
        public User(int id,String username, String phone, String password,String profile, int sex, String zodiac, String constellation) {
            this.id = id;
            this.username = username;
            this.phone = phone;
            this.password = password;
            this.profile = profile;
            this.sex = sex;
            this.zodiac = zodiac;
            this.constellation = constellation;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
        public String getProfile(){
            return profile;
        }
        public void setProfile(String profile){
            this.profile = profile;
        }
        public int getSex() {
            return sex;
        }

        public void setSex(int sex) {
            this.sex = sex;
        }

        public String getZodiac() {
            return zodiac;
        }

        public void setZodiac(String zodiac) {
            this.zodiac = zodiac;
        }

        public String getConstellation() {
            return constellation;
        }

        public void setConstellation(String constellation) {
            this.constellation = constellation;
        }
    }

    private Handler handler=new Handler(){//处理请求获取的数据

        @Override
        public void handleMessage(@NonNull Message msg) {
            Map<String,Object>map = (Map<String, Object>) msg.obj;
            User user = (User) map.get("user");
            if((boolean)map.get("auth")){//如果token未过期，无需重新登录
                //将token解析生成的用户信息存储在sharedPreference中
                SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
                editor.putInt("id", user.getId());
                editor.putString("username",user.getUsername());
                editor.putString("phone",user.getPhone());
                editor.putString("password",user.getPassword());
                editor.putInt("sex",user.getSex());
                editor.putString("profile",user.getProfile());
                editor.putString("zodiac",user.getZodiac());
                editor.putString("constellation",user.getConstellation());
                editor.commit();
                //直接跳转至首页
                Intent intent = new Intent(MainActivity.this,HomeActivity.class);
                startActivity(intent);
            }
            else{//token过期，需重新登录，跳转至登录界面
                Intent intent = new Intent(MainActivity.this,LoginActivity.class);
                startActivity(intent);
            }

            finish();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SharedPreferences pref = getSharedPreferences("data",MODE_PRIVATE);
        String token = pref.getString("token","");//获取token
        Log.d("token",token);
        if(token.equals("")){//如果token不存在，直接跳转登录界面
            Intent intent = new Intent(MainActivity.this,LoginActivity.class);
            startActivity(intent);
        }
        else {//token存在，请求解析token
            Log.d("token",token);
            getData(token);
        }

    }
    //发送网络请求，解析token
    private void getData(String token){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("http://8.142.19.67:3000/user")
                            .header("Authorization","Bearer "+token)
                            .build();
                    okHttpClient.newCall(request).enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Message message = new Message();
                            Map<String,Object>map = new HashMap<>();
                            map.put("auth",false);
                            message.obj = map;
                            handler.sendMessage(message);
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException,RuntimeException {
                            if (response.isSuccessful()) {
                                String res = response.body().string();
                                 Log.d("res",res);
                                try {
                                    Message message = new Message();
                                    if (res.equals("")) {
                                        Map<String,Object>map = new HashMap<>();
                                        map.put("auth",false);
                                        message.obj = map;
                                        handler.sendMessage(message);
                                    } else {
                                        JSONObject jsonObject = new JSONObject(res);
                                        int id = jsonObject.getInt("id");
                                        String username = jsonObject.getString("username");
                                        String phone = jsonObject.getString("phone");
                                        String password = jsonObject.getString("password");
                                        String profile = jsonObject.getString("profile");
                                        int sex = jsonObject.getInt("sex");
                                        String zodiac = jsonObject.getString("zodiac");
                                        String constellation = jsonObject.getString("constellation");
                                        User user = new User(id,username,phone,password,profile,sex,zodiac,constellation);
                                        Map<String,Object>map = new HashMap<>();
                                        map.put("auth",true);
                                        map.put("user",user);
                                      message.obj=map;
                                      handler.sendMessage(message);
                                    }
                                } catch (Exception e) {
                                    Message message = new Message();
                                    Map<String,Object>map = new HashMap<>();
                                    map.put("auth",false);
                                    message.obj = map;
                                    handler.sendMessage(message);
                                    e.printStackTrace();
                                }
                            }else {
                                Log.d("fail","hahaha");
                                Message message = new Message();
                                Map<String,Object>map = new HashMap<>();
                                map.put("auth",false);
                                message.obj = map;
                                handler.sendMessage(message);
                            }
                        }
                    });

                } catch (Exception e) {
                    Message message = new Message();
                    Map<String,Object>map = new HashMap<>();
                    map.put("auth",false);
                    message.obj = map;
                    handler.sendMessage(message);
                    e.printStackTrace();
                }
            }
        }).start();
    }


}
